/**
 * Copyright 2015-2016 eyaomall.cn
 * All rights reserved.
 *
 * @project
 * @author pro
 * @version 1.0
 * @date 2016-03-07
 */
package com.eyaomall.wxmall.interceptor;


import java.net.URLEncoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.eyaomall.wxmall.common.helper.MemberHelper;
import com.github.pagehelper.StringUtil;
import com.lycheeframework.core.common.helper.GlobEnv;

/**
 * 登录拦截器
 * @author pro
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	private static final Logger LOG = LoggerFactory.getLogger(LoginInterceptor.class);
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String shopId = request.getParameter("shopId");
		LOG.error("shopId" + shopId);
		if(MemberHelper.getId() == null || MemberHelper.getId() <= 0){
			LOG.error("LoginInterceptor");
			
			if(StringUtil.isEmpty(shopId)){
				shopId = MemberHelper.getShopId() > 0 ? String.valueOf(MemberHelper.getShopId()) : null;
			}
			
			if(StringUtil.isNotEmpty(shopId)){
				
				String redirect=URLEncoder.encode(GlobEnv.getWebURL("")+request.getServletPath()  + "?" + request.getQueryString(),"utf-8");
				
				response.sendRedirect(GlobEnv.getWebURL("verify") + "?shopId=" + shopId+"&redirect="+redirect);
			}else{
				response.sendRedirect(GlobEnv.getWebURL("error/error"));
			}
			
			return false;
		}else{
			if(StringUtil.isNotEmpty(shopId) && !shopId.equals(String.valueOf(MemberHelper.getShopId()))){
				MemberHelper.cleanAll();
				
				String redirect=URLEncoder.encode(GlobEnv.getWebURL("")+request.getServletPath()  + "?" + request.getQueryString(),"utf-8");
				
				response.sendRedirect(GlobEnv.getWebURL("verify") + "?shopId=" + shopId+"&redirect="+redirect);
			}
		}
		
		return true;
	}
	
}
